<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

// 修改 sites 数组，将其改为计算属性
const sites = computed(() => {
  const role = parseInt(localStorage.getItem('role'))
  const isAdmin = parseInt(localStorage.getItem('isAdmin'))
  
  const baseMenus = ['公告', '问题反馈', '论坛', '知识库', '分析']
  
  if (role === 0 || isAdmin === 1) {
    return [
      ...baseMenus.slice(0, 2),
      '任务',
      ...baseMenus.slice(2)
    ]
  }
  
  return baseMenus
})

// 用户信息
const realname = ref(localStorage.getItem('realname'))
const isAdmin = ref(localStorage.getItem('isAdmin') === '1')
const role = ref(localStorage.getItem('role') === '0')

// 当前激活的一级菜单
const currentSite = computed(() => {
  const path = route.path
  if (path.startsWith('/admin/')) {
    return ''
  }
  
  if (path === '/') return '公告'
  if (path.startsWith('/daily-report')) return '问题反馈'
  if (path.startsWith('/task')) return '任务'
  if (path.startsWith('/forum') || path.startsWith('/reply')) return '论坛'
  if (path.startsWith('/knowledge/')) return '知识库' // 统一处理所有知识库路径
  if (path.startsWith('/analysis')) return '分析'
  if (path.startsWith('/login') || path.startsWith('/logout')) return '登录'
  return '公告'
})

// 当前激活的二级菜单
const currentSubMenu = computed(() => {
  const path = route.path
  if (path.startsWith('/knowledge/')) {
    const subPath = path.split('/')[2]
    if (subPath === 'sop') return 'SOP' // 明确处理 SOP 路径
    if (subPath === 'learning') return 'Learning'
    return subPath.charAt(0).toUpperCase() + subPath.slice(1)
  } else if (path.startsWith('/analysis/')) {
    const subPath = path.split('/')[2]
    return subPath.charAt(0).toUpperCase() + subPath.slice(1)
  }
  return ''
})

// 添加 isUserMenuActive 计算属性
const isUserMenuActive = computed(() => {
  return route.path.startsWith('/user/') || route.path.startsWith('/admin/')
})

// 用户菜单
const subMenus = {
  '用户': ['个人信息', ...(isAdmin.value ? ['后台管理'] : []), '注销']
}

// 菜单状态
const showUserMenu = ref(false)
const knowledgeSubMenuVisible = ref(route.path.startsWith('/knowledge/'))

// 监听路由变化
watch(() => route.path, (newPath) => {
  if (newPath.startsWith('/knowledge/')) {
    knowledgeSubMenuVisible.value = true
  }
})

// 菜单点击处理
const handleMenuClick = (site) => {
  if (site === '公告') {
    router.push('/')
  } else if (site === '问题反馈') {
    router.push('/daily-report')
  } else if (site === '任务') {
    router.push('/task')
  } else if (site === '论坛') {
    router.push('/forum')
  } else if (site === '知识库') {
    // 保持当前子路径
    if (!route.path.startsWith('/knowledge/')) {
      router.push('/knowledge/learning')
    }
  } else if (site === '分析') {
    router.push('/analysis/profiler')
  } else if (site === '登录') {
    router.push('/login')
  }
}

// 用户菜单点击处理
const handleUserMenuClick = (item) => {
  if (item === '注销') {
    handleLoginLogout()
  } else if (item === '个人信息') {
    router.push('/user/personal')
    showUserMenu.value = false
  } else if (item === '后台管理') {
    router.push('/admin/employees')
    showUserMenu.value = false
  }
}

const clearAuthCache = () => {
  const keys = ['realname', 'isAdmin', 'token', 'userId', 'role', 'username', 'userEmail']
  keys.forEach((key) => localStorage.removeItem(key))
  if (typeof window !== 'undefined') {
    window.dispatchEvent(new CustomEvent('user-info-updated'))
  }
}

// 登录/注销处理
const handleLoginLogout = () => {
  if (realname.value) {
    clearAuthCache()
    realname.value = null
    isAdmin.value = false
    router.push('/login')
  } else {
    router.push('/login')
  }
}

// 鼠标离开用户菜单
const handleMouseLeave = () => {
  showUserMenu.value = false
}

// 初始化
onMounted(() => {
  realname.value = localStorage.getItem('realname')
  isAdmin.value = localStorage.getItem('isAdmin') === '1'
})
</script>

<template>
  <header class="header">
    <div class="logo">
      <a href="/"><img src="/logo.png" alt="Logo" /></a>
      <span>现场问题反馈系统</span>
    </div>
    <nav class="site-nav">
      <!-- 一级菜单 -->
      <div 
        v-for="site in sites" 
        :key="site" 
        class="nav-item"
      >
        <button
          :class="{ active: currentSite === site }"
          @click="handleMenuClick(site)"
        >
          {{ site }}
        </button>
      </div>

      <!-- 用户菜单 -->
      <div class="nav-item" @mouseleave="handleMouseLeave">
        <button 
          @click="realname ? showUserMenu = !showUserMenu : router.push('/login')"
          :class="{ active: isUserMenuActive }"
        >
          {{ realname ? realname : '登录' }}
        </button>
        
        <!-- 用户二级菜单 -->
        <div v-if="realname && showUserMenu" class="submenu user-submenu">
          <button
            v-for="subItem in subMenus['用户']"
            :key="subItem"
            :class="{ active: currentUserMenu === subItem }"
            @click="handleUserMenuClick(subItem)"
          >
            {{ subItem }}
          </button>
        </div>
      </div>
    </nav>
  </header>
</template>

<style scoped>
.header {
  background-color: #fff;
  padding: 1rem 2rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.logo {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.logo img {
  height: 40px;
}

.logo span {
  font-size: 1.5rem;
  font-weight: bold;
  color: #333;
}

.site-nav {
  display: flex;
  gap: 1rem;
}

.site-nav button {
  padding: 0.5rem 1rem;
  border: none;
  background: none;
  color: #666;
  cursor: pointer;
  font-size: 1rem;
  transition: all 0.2s;
  position: relative;
}

.site-nav button.active {
  color: #0052cc;
  font-weight: bold;
}

.site-nav button.active::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 50%;
  transform: translateX(-50%);
  width: 20px;
  height: 2px;
  background-color: #0052cc;
}

.nav-item {
  position: relative;
}

.submenu {
  position: absolute;
  top: 100%;
  left: 0;
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  border-radius: 4px;
  padding: 0.5rem 0;
  min-width: 120px;
  z-index: 1001;
}

.submenu button {
  display: block;
  width: 100%;
  text-align: center;
  padding: 0.5rem 1rem;
  border: none;
  background: none;
  color: #666;
  cursor: pointer;
  font-size: 1rem;
  transition: all 0.2s;
}

.submenu button:hover {
  background-color: #f5f5f5;
  color: #0052cc;
}

.submenu button.active {
  color: #0052cc;
  font-weight: bold;
  background-color: #f0f7ff;
}

.user-submenu {
  right: 0;
  left: auto;
}

.user-submenu button {
  text-align: left;
  padding: 8px 16px;
  position: relative;
}

.user-submenu button.active::after {
  content: '';
  position: absolute;
  bottom: 4px;
  left: 50%;
  transform: translateX(-50%);
  width: 20px;
  height: 2px;
  background-color: #409EFF;
}
</style>
